<template>
  <div class="app-container">
    <el-row>
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm el-form-bottom"
      >
        <el-divider content-position="left"
          ><legend class="divider-line">基本信息</legend></el-divider
        >
        <el-col :span="8">
          <el-form-item label="类型名称" prop="name">
            <el-input v-model="ruleForm.name"></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="权重" prop="sort">
            <el-input-number
              v-model="ruleForm.sort"
              :min="0"
              :max="99"
              :step="1"
              step-strictly
            ></el-input-number>
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="关联规格">
            <el-button
              type="warning"
              @click.prevent="chooseNorm"
              icon="el-icon-search"
              >选择</el-button
            >
            <span class="relation-title">规格只能选择不能输入</span>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="已选规格">
            <el-input v-model="ruleForm.normNames" readonly></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="关联品牌">
            <el-button
              type="warning"
              @click.prevent="chooseBrand"
              icon="el-icon-search"
              >选择</el-button
            >
            <span class="relation-title">品牌只能选择不能输入</span>
            <el-input
              v-model="ruleForm.brandNames"
              readonly
              style="display: none"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="已选品牌" prop="brandNames">
            <el-input v-model="ruleForm.brandNames" readonly></el-input>
          </el-form-item>
        </el-col>

        <el-divider content-position="left"
          ><legend class="divider-line">
            检索属性，可添加多个
          </legend></el-divider
        >

        <el-col :span="8">
          <el-form-item>
            <el-button
              type="warning"
              @click="addDomain"
              icon="el-icon-circle-plus-outline"
              >添加</el-button
            >
          </el-form-item>
        </el-col>

        <el-col
          class="add_norm"
          :span="16"
          v-for="(item, index) in domains"
          :key="item.key"
        >
          <el-form-item label="属性名称" prop="attrName">
            <el-input v-model="item.name" maxlength="20"></el-input>
          </el-form-item>
          <el-form-item label="属性值" prop="attrVal">
            <el-input v-model="item.value"></el-input>
          </el-form-item>
          <el-button
            v-show="index != 0"
            @click.prevent="removeDomain(item)"
            icon="el-icon-delete"
            circle
          ></el-button>
          <el-input v-model="item.id" style="display: none"></el-input>
        </el-col>

        <el-divider content-position="left"
          ><legend class="divider-line">
            自定义属性，可添加多个
          </legend></el-divider
        >

        <el-col :span="8">
          <el-form-item>
            <el-button
              type="warning"
              @click="addCustom"
              icon="el-icon-circle-plus-outline"
              >添加</el-button
            >
          </el-form-item>
        </el-col>

        <el-col
          class="add_norm"
          :span="16"
          v-for="(item, index) in customs"
          :key="item.key"
        >
          <el-form-item label="属性名称" prop="attrName">
            <el-input v-model="item.name"></el-input>
          </el-form-item>
          <el-button
            v-show="index != 0"
            @click.prevent="removeCustom(item)"
            icon="el-icon-delete"
            circle
          ></el-button>
          <el-input v-model="item.id" style="display: none"></el-input>
        </el-col>
      </el-form>
      <div class="fixed-bottom-20">
        <el-button type="primary" @click="submitForm('ruleForm')"
          >立即提交</el-button
        >
        <el-button type="success" @click="back">返回</el-button>
        <el-button @click="resetForm('ruleForm')">重置</el-button>
      </div>
    </el-row>

    <el-dialog
      title="选择规格"
      destroy-on-close
      :visible.sync="dialogFormVisible"
    >
      <el-table
        ref="normTable"
        :data="normList"
        border
        height="350"
        tooltip-effect="dark"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55"> </el-table-column>
        <el-table-column label="规格名称" prop="name"> </el-table-column>
        <el-table-column prop="sort" label="权重"> </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="updateNormData">
          确定
        </el-button>
      </div>
    </el-dialog>
    <el-dialog
      title="选择品牌"
      destroy-on-close
      :visible.sync="dialogBrandVisible"
    >
      <el-table
        ref="brandTable"
        :data="brandList"
        border
        height="350"
        tooltip-effect="dark"
        style="width: 100%"
        @selection-change="handleSelectionBrand"
      >
        <el-table-column type="selection" width="55"> </el-table-column>
        <el-table-column label="品牌名称" prop="name"> </el-table-column>
        <el-table-column prop="sort" label="权重"> </el-table-column>
        <el-table-column prop="createUser" label="创建人"> </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogBrandVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="updateBrandData">
          确定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {
  updateType,
  getNormList,
  getBrandList,
  editType,
  brandByIds,
  normByIds
} from "@/api/product";
import { Message } from "element-ui";
export default {
  name: "normAdd",
  data() {
    return {
      normList: [], // 规格列表
      brandList: [], // 品牌列表
      ruleForm: {
        name: "",
        sort: "",
        normNames: "",
        productNormIds: "",
        brandNames: "",
        productBrandIds: ""
      },
      domains: [
        {
          name: "",
          value: ""
        }
      ],
      customs: [
        {
          name: ""
        }
      ],
      rules: {
        name: [
          { required: true, message: "请输入类型名称", trigger: "blur" },
          { max: 20, message: "类型名称不能超过20个字符", trigger: "blur" }
        ],
        sort: [{ required: true, message: "请填写权重", trigger: "blur" }],
        brandNames: [
          { required: true, message: "请选择关联品牌", trigger: "blur" }
        ]
      },
      dialogFormVisible: false,
      dialogBrandVisible: false,
      multipleSelection: [],
      multipleSelection1: [],
      hasSelectList: [], // 默认选中品牌
      hasNormList: [] // 默认选中规格
    };
  },
  created() {
    this.typeId = this.$route.query.id;
    this.getData(this.typeId);
  },
  methods: {
    getData(id) {
      editType({ id: id }).then(res => {
        this.domains = res.data.data.attr;
        this.customs = res.data.data.custAttr;
        this.ruleForm = res.data.data.type;
        this.$set(
          this.ruleForm,
          "productBrandIds",
          res.data.data.type.productBrandIds
        );
        this.$set(
          this.ruleForm,
          "productNormIds",
          res.data.data.type.productNormIds
        );
        this.getNames();
      });
    },
    getNames() {
      // 根据id过滤数组，获取对应选中的name值
      brandByIds({ ids: this.ruleForm.productBrandIds }).then(res2 => {
        this.$set(this.ruleForm, "brandNames", res2.data.rows);
        // this.ruleForm.brandNames = res2.data.rows
      });
      if (!this.ruleForm.productNormIds) return;
      normByIds({ ids: this.ruleForm.productNormIds }).then(res1 => {
        this.$set(this.ruleForm, "normNames", res1.data.rows);
        // this.ruleForm.normNames = res1.data.rows
      });
    },
    handleSelectionChange(val) {
      // 选中规格行信息
      this.multipleSelection = val;
    },
    handleSelectionBrand(val) {
      // 选中品牌行信息
      this.multipleSelection1 = val;
    },
    addDomain() {
      // 新增检索属性
      this.domains.push({
        name: "",
        value: "",
        key: Date.now()
      });
    },
    addCustom() {
      // 新增自定义属性
      this.customs.push({
        name: "",
        key: Date.now()
      });
    },
    removeDomain(item) {
      // 移出检索属性
      var index = this.domains.indexOf(item);
      if (index !== 0) {
        this.domains.splice(index, 1);
      }
    },
    removeCustom(item) {
      // 移出自定义属性
      var index = this.customs.indexOf(item);
      if (index !== 0) {
        this.customs.splice(index, 1);
      }
    },
    chooseNorm() {
      this.dialogFormVisible = true;
      // 获取关联规格列表
      getNormList().then(res => {
        this.normList = res.data.rows;
        this.hasNormList = this.ruleForm.productNormIds.split(",");
        this.checkNormRow(this.hasNormList, res.data.rows);
      });
    },
    chooseBrand() {
      this.dialogBrandVisible = true;
      // 获取关联品牌列表
      getBrandList().then(res => {
        this.brandList = res.data.rows;
        this.hasSelectList = this.ruleForm.productBrandIds.split(",");
        this.checkBrandRow(this.hasSelectList, res.data.rows);
      });
    },
    checkBrandRow(checkId, data) {
      data.map(item => {
        checkId.map(el => {
          if (el == item.id) {
            this.toggleBrandSelection(item, true);
          }
        });
      });
    },
    toggleBrandSelection(row, select) {
      if (row) {
        this.$nextTick(() => {
          this.$refs.brandTable &&
            this.$refs.brandTable.toggleRowSelection(row, select);
        });
      }
    },
    checkNormRow(checkId, data) {
      data.map(item => {
        checkId.map(el => {
          if (el == item.id) {
            this.toggleNormSelection(item, true);
          }
        });
      });
    },
    toggleNormSelection(row, select) {
      if (row) {
        this.$nextTick(() => {
          this.$refs.normTable &&
            this.$refs.normTable.toggleRowSelection(row, select);
        });
      }
    },
    updateNormData() {
      // 确认关联规格
      if (this.multipleSelection.length > 2) {
        Message.error("规格最多选择2个");
        return;
      }
      let [names, ids] = ["", ""];
      for (let i in this.multipleSelection) {
        names += this.multipleSelection[i].name + ",";
        ids += this.multipleSelection[i].id + ",";
      }
      if (this.multipleSelection.length > 0) {
        this.ruleForm.normNames = names.substring(0, names.lastIndexOf(","));
        this.ruleForm.productNormIds = ids.substring(0, ids.lastIndexOf(","));
        this.dialogFormVisible = false;
      }
    },
    updateBrandData() {
      // 确认关联品牌
      let [names, ids] = ["", ""];
      for (let i in this.multipleSelection1) {
        names += this.multipleSelection1[i].name + ",";
        ids += this.multipleSelection1[i].id + ",";
      }
      if (this.multipleSelection1.length > 0) {
        this.ruleForm.brandNames = names.substring(0, names.lastIndexOf(","));
        this.ruleForm.productBrandIds = ids.substring(0, ids.lastIndexOf(","));
        this.dialogBrandVisible = false;
      }
    },
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          for (let i in this.domains) {
            if (this.domains[i].name == "") {
              Message.error("属性名称不能为空");
              return;
            }
            if (this.domains[i].value == "") {
              Message.error("属性值不能为空");
              return;
            }
          }
          for (let j in this.customs) {
            if (
              this.customs[j].name == "" ||
              this.customs[j].name == undefined
            ) {
              Message.error("属性名称不能为空");
              return;
            }
          }
          let jsonString = "[{";
          // 检索属性
          if (this.domains && this.domains.length > 0) {
            for (let i in this.domains) {
              let id = this.domains[i].id;
              let name = this.domains[i].name;
              let val = this.domains[i].value;
              if (id == "" || id == undefined) id = 0;
              if (name != "" && typeof name != "undefined") {
                jsonString +=
                  '"id":"' +
                  id +
                  '","name":"' +
                  name +
                  '","type":"1","val":"' +
                  val +
                  '"},{';
              }
            }
          }
          // 自定义属性
          if (this.customs && this.customs.length > 0) {
            for (let j in this.customs) {
              let id = this.customs[j].id;
              let name = this.customs[j].name;
              if (id == "" || id == undefined) id = 0;
              jsonString +=
                '"id":"' +
                id +
                '","name":"' +
                name +
                '","type":"2","val":""},{';
            }
          }
          jsonString = jsonString.substring(0, jsonString.lastIndexOf(","));
          jsonString += "]";
          this.ruleForm.id = this.typeId;
          this.ruleForm.attrVal = jsonString;
          updateType(this.ruleForm).then(res => {
            if (!res.data.success) {
              Message.error(res.data.message);
              return;
            }
            Message.success("操作成功");
            history.back();
          });
        }
      });
    },
    resetForm(formName) {
      this.getData(this.typeId);
    },
    back() {
      history.back();
    }
  }
};
</script>
<style scoped>
/deep/ .avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
/deep/ .avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
/deep/ [class*="el-col-"] {
  float: none;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.add_norm {
  display: flex;
}
.add_norm .el-form-item {
  width: 35%;
}
.add_norm .el-button {
  height: 36px;
  margin-left: 15px;
}

.el-divider {
  margin: 30px 0;
}
.divider-line {
  font-size: 20px;
  font-weight: 300;
}
.relation-title {
  color: #999 !important;
  margin-left: 15px;
}
</style>
